<!--
 * @Description: 
 * @Author: chenju
 * @Date: 2021-08-11 15:40:47
 * @LastEditors: chenju
 * @LastEditTime: 2023-02-01 10:29:50
-->
<template>
  <el-tooltip v-bind="attrs" :get-popup-container="getPopupContainer" :visible="tooltipVisible">
    <template #content>
      <slot name="content"></slot>
    </template>
    <div
      style="max-width: 100%; line-height: 100%"
      :style="wrapStyle"
      @mouseenter="handleMouseEnter"
      @mouseleave="handleMouseLeave"
    >
      <!-- NOTE 插槽内的元素需要一个完整的可以带省略号的元素（块级元素） -->
      <!-- 示例：<div class="g-ell" style="width: 200px">这里是很长很长的文本这里是很长很长的文本这里是很长很长的文本这里是很长很长的文本</div> -->
      <slot></slot>
    </div>
  </el-tooltip>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import { throttle } from 'lodash';

// NOTE 外层元素需要设置宽度，否则内部无法判断是否需要超出隐藏
export default defineComponent({
  name: 'DTooltip',
  props: {
    wrapStyle: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  setup(props, { attrs }) {
    const getPopupContainer = (trigger: HTMLElement) => {
      return trigger.parentElement;
    };

    const tooltipVisible = ref(false);

    /**
     * @Description: 鼠标移入描述时判断是否需要显示tooltip
     * @param {*} e
     * @param {*} item
     * @return {*}
     */
    const handleMouseEnter = throttle((e: MouseEvent) => {
      console.log(
        'handleMouseEnter',
        (e.target as any).children[0].scrollWidth,
        (e.target as any).children[0].offsetWidth,
        (e.target as any).children[0].scrollWidth > (e.target as any).children[0].offsetWidth
      );
      console.log(
        'handleMouseEnter height',
        (e.target as any).children[0].scrollHeight,
        (e.target as any).children[0].offsetHeight,
        (e.target as any).children[0].scrollHeight > (e.target as any).children[0].offsetHeight
      );
      if (
        (e.target as any).children[0].scrollWidth > (e.target as any).children[0].offsetWidth ||
        (e.target as any).children[0].scrollHeight > (e.target as any).children[0].offsetHeight
      ) {
        // console.log('出现了省略号');
        tooltipVisible.value = true;
      } else {
        // console.log('没有出现省略号');
        tooltipVisible.value = false;
      }
    }, 200);

    /**
     * @Description: 鼠标移出
     * @param {*} item
     * @return {*}
     */
    const handleMouseLeave = throttle(() => {
      tooltipVisible.value = false;
    }, 200);

    return {
      getPopupContainer,
      tooltipVisible,
      handleMouseEnter,
      handleMouseLeave,
      attrs
    };
  }
});
</script>
